package priv.dajie.tzzq.common;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName SqlSessionFactoryUtils
 * @Description
 * @Author dajie
 * @Date 2019/10/15 1:22 下午
 * @Version V1.0
 **/
public class SqlSessionFactoryUtils {
    private static SqlSessionFactory sqlSessionFactory = null;

    private static void init(){
        synchronized (SqlSessionFactory.class){
            String resource = "config/mybatis/mybatis-config.xml";
            if (sqlSessionFactory == null){
                InputStream inputStream = null;
                try{
                    inputStream = Resources.getResourceAsStream(resource);
                    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                finally {
                    if (inputStream!=null){
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public static SqlSession openSession(){
        if(sqlSessionFactory == null){
            init();
        }
        return sqlSessionFactory.openSession();
    }

}
